package tq.com.tqteacher.activity.captureVideo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.ViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.githang.statusbar.StatusBarCompat;

import java.text.SimpleDateFormat;
import java.util.BitSet;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import tq.com.easysurfacecapture.TQCaputreView;
import tq.com.easysurfacecapture.TQOpencvRecord;
import tq.com.systools.system.FileHelper;
import tq.com.systools.system.StringHelper;
import tq.com.tqcom.base.BaseActivity;
import tq.com.tqcom.util.TQLoadingHelper;
import tq.com.tqcom.view.TQHeader5View;
import tq.com.tqteacher.R;
import tq.com.tqteacher.activity.TQCropPictureActivity;
import tq.com.tqteacher.view.TQHeader3ViewHold;

public class TQCaptureActivity extends BaseActivity {
    private TQHeader5View mHeader5View;
    private TQCaputreView mTQCaputreView;
    private TextView timeView;

//    private ImageButton mHuabi;
//    private ImageButton mHuaping;
//    private ImageButton finish;
    private TQOpencvRecord mRecord = new TQOpencvRecord();

    private String picUrl;
    private String recordPath;

    static public String PIC_URL_PARAM ="PIC_URL_PARAM";
    static public String RESULT_KEY = "RESULT_KEY";

    static public void requestCapture(String pPicUrl, Activity pActivity, int requestCode){
        Intent intent = new Intent(pActivity, TQCaptureActivity.class);
        if(!StringHelper.isEmpty(pPicUrl)){
            intent.putExtra(PIC_URL_PARAM, pPicUrl);
        }
        pActivity.startActivityForResult(intent, requestCode);
    }

    static public void requestCapture(String pPicUrl, Fragment pActivity, int requestCode){
        Intent intent = new Intent(pActivity.getContext(), TQCaptureActivity.class);
        if(!StringHelper.isEmpty(pPicUrl)){
            intent.putExtra(PIC_URL_PARAM, pPicUrl);
        }
        pActivity.startActivityForResult(intent, requestCode);
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStatusBar();
        setContentView(R.layout.activity_capture_layout);
        mHeader5View = findViewById(R.id.title);
        mHeader5View.getTitleView().setText("录课");
        mHeader5View.getBackIcon().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TQCaptureActivity.this.finish();
            }
        });

        mTQCaputreView = findViewById(R.id.captureView);
        picUrl = getIntent().getStringExtra(PIC_URL_PARAM);

        timeView = findViewById(R.id.time);

        if(picUrl != null){
            if(FileHelper.isFileExists(picUrl)){
                mTQCaputreView.setPicture(picUrl);
            }else if(picUrl.length() > 0){

                RequestOptions lOptions = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.RESOURCE);

                Glide.with(this).load(picUrl).apply(lOptions).into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                        Log.d(TAG, "onResourceReady: ");
                        findViewById(R.id.capture_hb).getRight();

                        if(resource instanceof BitmapDrawable){
                            mTQCaputreView.setPicture(((BitmapDrawable)resource).getBitmap());
                        }else{
                            mTQCaputreView.setPicture(drawableToBitmap(resource));
                        }
                    }
                });
            }

        }

        findViewById(R.id.capture_hb).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTQCaputreView.setAction(TQCaputreView.ACTION_PAINT_PATH);
            }
        });

        findViewById(R.id.capture_hp).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTQCaputreView.setAction(TQCaputreView.ACTION_SCROLL);
            }
        });

        findViewById(R.id.capture_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRecord.stopRecording();
                stopCapture();
            }
        });
        findViewById(R.id.capture_remove).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTQCaputreView.removeLast();
            }
        });
        mRecord.initRecord(mTQCaputreView);

        findViewById(R.id.capture_start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                findViewById(R.id.mask).setVisibility(View.GONE);
                findViewById(R.id.capture_start).setVisibility(View.GONE);

                TQLoadingHelper.build(TQCaptureActivity.this).setCancelable(false).show();
                TQLoadingHelper.setText("正在载入");
                startRecord();
            }
        });
        findViewById(R.id.capture_start).setVisibility(View.VISIBLE);
        findViewById(R.id.mask).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        findViewById(R.id.mask).setVisibility(View.VISIBLE);
//        TQLoadingHelper.build(this).setCancelable(false).show();
//        TQLoadingHelper.setText("正在载入");
//
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                startRecord();
//                mTimer.schedule(mTimerTask, 1000, 1000);
//            }
//        }, 1000);


    }

    public void startRecord(){
        mTimer.schedule(mTimerTask, 1000, 1000);
        recordPath = FileHelper.videoCacheFile();
        mRecord.startRecording(recordPath);
        TQLoadingHelper.dimiss();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mRecord.isRecording()){
            mRecord.stopRecording();
        }

        mTimer.cancel();
    }

    private void stopCapture(){
        Intent intent = new Intent();
        intent.putExtra(RESULT_KEY, recordPath);

        setResult(RESULT_OK, intent);
        finish();
    }

    private Handler mHandler = new Handler();
    private long mLongTime = 0;
    private Timer mTimer = new Timer();
    private TimerTask mTimerTask = new TimerTask() {
        @Override
        public void run() {
            mLongTime++;

            SimpleDateFormat lDateFormat = new SimpleDateFormat("HH:mm:ss");
            lDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            final String str = lDateFormat.format(mLongTime * 1000);

            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    timeView.setText(str);
                }
            });
        }
    };


    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }
}
